import React, { Component, Fragment } from 'react';
import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import { connect } from 'dva';
import {
  Icon,
  Card,
  Divider,
  Badge,
  Table,
  Select,
  message,
  Button,
  Dropdown,
  Menu,
  Modal,
  Form,
  Row,
  Col,
  Input,
} from 'antd';
import classNames from 'classnames';
import DescriptionList from '@/components/DescriptionList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from './AdvancedProfile.less';
import shallowCompare from 'react-addons-shallow-compare'; // ES6
import ChangePwd from './changePwd';
import UploadFile from './uploadFile';
import DrawerComponent from './drawerInfo';
import Uploaddrawer from './uploaddrawer';
import SelectBank from './selectBank';
import MembersComponent from './members';

const { Description } = DescriptionList;
const ButtonGroup = Button.Group;
const FormItem = Form.Item;

const description = data => (
  <DescriptionList className={styles.headerList} size="small" col="3">
    <Description term="账号编号">{data.accountNo}</Description>
    <Description term="企业标识">{data.userName}</Description>
    <Description term="手机号">{data.mobile}</Description>
  </DescriptionList>
);

const operationTabList = [
  {
    key: 'tab1',
    tab: '交易记录',
  },
];
const status = text => {
  if (text === 0) {
    return '提交申请';
  } else if (text === 1) {
    return '成功';
  } else if (text === 2) {
    return '处理中 ';
  } else {
    return '失败';
  }
};
const columns = [
  {
    title: '企业名称',
    dataIndex: 'enterpriseName',
    key: 'enterpriseName',
  },
  {
    title: '交易类型',
    dataIndex: 'type',
    key: 'type',
    render: text => {
      return <div>{text === 5 ? '充值' : '提现'}</div>;
    },
  },
  {
    title: '交易金额',
    dataIndex: 'amount',
    key: 'amount',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    render: text => {
      return status(text);
    },
  },
  {
    title: '交易时间',
    dataIndex: 'createTime',
    key: 'createTime',
  },
];

@connect(({ Account, loading }) => ({
  Account,
}))
@Form.create()
class AdvancedProfile extends Component {
  state = {
    operationkey: 'tab1',
    stepDirection: 'horizontal',
    modalVisible: false,
    visibleDrawer: false,
    visibleUploadDrawer: false,
    bankModalVisible: false,
    uploadFileVisible: false,
    memberVisible: false,
    selectedRows: {},
  };

  shouldComponentUpdate(nextProps, nextState) {
    return shallowCompare(this, nextProps, nextState);
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'Account/fetch',
    });
    dispatch({
      type: 'Account/enterpriseList',
    });
    dispatch({
      type: 'Account/withdrawRecord',
      payload: {
        pageSize: 15,
      },
    });
  }

  componentWillUnmount() {}

  onOperationTabChange = key => {
    this.setState({ operationkey: key });
  };

  handleModalVisible = (flag, record) => {
    this.setState({
      modalVisible: flag,
    });
  };
  handleUploadModalVisible = (flag, record) => {
    this.setState({
      uploadFileVisible: flag,
      selectedRows: record,
    });
  };
  handleUpload = formVals => {
    console.log(formVals);
    const { dispatch } = this.props;
    const { selectedRows } = this.state;
    let _this = this;
    dispatch({
      type: 'Account/accountUpload',
      payload: { ...formVals, enterpriseNo: selectedRows.enterpriseNo },
      callback(res) {
        if (res.code === 200) {
          message.success('上传成功');
          _this.setState({
            uploadFileVisible: false,
          });
        }
      },
    });
  };
  handleChangePwd = data => {
    let _this = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'Account/updatePwd',
      payload: data,
      callback(res) {
        if (res.code === 200) {
          message.success('修改成功');
          _this.setState({
            modalVisible: false,
          });
        } else {
          message.error(res.errMsg);
        }
      },
    });
  };
  changeOrderPwd = record => {
    const { dispatch } = this.props;
    dispatch({
      type: 'Account/tradePwd',
      payload: {
        enterpriseNo: record.enterpriseNo,
      },
      callback(res) {
        console.log(res);
        if (res.code === 200) {
          window.open(res.msg.url);
        } else {
          message.error(res.errMsg);
        }
      },
    });
  };
  changeOpen = record => {
    const { dispatch } = this.props;
    dispatch({
      type: 'Account/openAccount',
      payload: {
        code: record.enterpriseNo,
      },
      callback(res) {
        if (res.code === 200) {
          window.open(res.msg.businessId);
        } else {
          message.error(res.errMsg);
        }
      },
    });
  };
  handleBindCard = (flag, record) => {
    const { dispatch } = this.props;
    const _this = this;
    if (flag) {
      dispatch({
        type: 'Account/bankList',
        payload: {},
        callback() {
          _this.setState({
            bankModalVisible: true,
            selectedRows: record,
          });
        },
      });
    }
  };
  handleMemberVisible = (flag, record) => {
    const { dispatch } = this.props;
    const _this = this;
    if (flag) {
      dispatch({
        type: 'Account/memberList',
        payload: {},
        callback() {
          _this.setState({
            memberVisible: true,
            selectedRows: record,
          });
        },
      });
    }
  };
  handleDelBankCard = e => {
    const { dispatch } = this.props;
    Modal.confirm({
      title: '确认',
      content: '确定解绑银行卡吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        dispatch({
          type: 'Account/delBackCard',
          payload: {
            enterpriseNo: e.enterpriseNo,
          },
          callback(res) {
            if (res.code === 200) {
              message.success('解绑成功');
              dispatch({
                type: 'Account/enterpriseList',
              });
            } else {
              message.error(res.errMsg);
            }
          },
        });
      },
    });
  };
  handleUploadDrawer = (flag, recod) => {
    const { dispatch } = this.props;
    console.log(flag);
    let _this = this;
    if (flag) {
      dispatch({
        type: 'Account/accountDatas',
        payload: { enterpriseNo: recod.enterpriseNo },
        callback() {
          _this.setState({
            visibleUploadDrawer: true,
          });
        },
      });
    } else {
      this.setState({
        visibleUploadDrawer: false,
      });
    }
  };

  visibleDrawerInfo = (flag, recod) => {
    const { dispatch } = this.props;
    let _this = this;
    if (flag) {
      dispatch({
        type: 'Account/getEnterpriseDesc',
        payload: { code: recod.enterpriseNo },
        callback() {
          _this.setState({
            visibleDrawer: true,
          });
        },
      });
    } else {
      this.setState({
        visibleDrawer: false,
      });
    }
  };
  handleBankModalVisible = () => {
    this.setState({
      bankModalVisible: false,
    });
  };
  handleMemberModalVisible = () => {
    this.setState({
      memberVisible: false,
    });
  };
  handleSelectBank = val => {
    let _this = this;
    const { dispatch } = this.props;
    const { selectedRows } = this.state;
    dispatch({
      type: 'Account/bandBackCard',
      payload: {
        enterpriseNo: selectedRows.enterpriseNo,
        ...val,
      },
      callback(res) {
        if (res.code === 200) {
          window.open(res.msg.url);
          _this.setState({
            bankModalVisible: false,
          });
        } else {
          message.error(res.errMsg);
        }
      },
    });
  };
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    this.setState({
      pagination: {
        pageNo: pagination.current,
        pageSize: 15,
      },
    });
    const params = {
      pageNo: pagination.current,
      pageSize: 15,
      ...formValues,
    };
    dispatch({
      type: 'Account/withdrawRecord',
      payload: params,
    });
  };
  handleSearch = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
      });
      dispatch({
        type: 'Account/withdrawRecord',
        payload: values,
      });
    });
  };
  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'Account/withdrawRecord',
      payload: {},
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="企业名称">
              {getFieldDecorator('enterpriseName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="状态">
              {getFieldDecorator('status')(
                <Select placeholder="请选择状态" style={{ width: '100%' }}>
                  <Select.Option value={0} key={0}>
                    全部
                  </Select.Option>
                  <Select.Option value={1} key={1}>
                    成功
                  </Select.Option>
                  <Select.Option value={2} key={2}>
                    处理中
                  </Select.Option>
                  <Select.Option value={3} key={3}>
                    失败
                  </Select.Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="类型">
              {getFieldDecorator('type')(
                <Select placeholder="请选择状态" style={{ width: '100%' }}>
                  <Select.Option value={2} key={2}>
                    提现
                  </Select.Option>
                  <Select.Option value={1} key={1}>
                    充值
                  </Select.Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  render() {
    const {
      modalVisible,
      visibleDrawer,
      visibleUploadDrawer,
      bankModalVisible,
      memberVisible,
      uploadFileVisible,
    } = this.state;
    const {
      Account: {
        data,
        companyList,
        companyDesc = {},
        bankList,
        memberList,
        withdrawRecordList = [],
      },
    } = this.props;
    const { loading } = this.props;
    const action = (
      <Fragment>
        <ButtonGroup>
          <Button onClick={() => this.handleModalVisible(true)}>修改密码</Button>
        </ButtonGroup>
      </Fragment>
    );
    console.log(withdrawRecordList);
    let pagination = {
      pageNo: withdrawRecordList ? withdrawRecordList.pageNo : '',
      total: withdrawRecordList ? withdrawRecordList.total : '',
      pageSize: withdrawRecordList ? withdrawRecordList.pageSize : 15,
    };
    const status = [
      {
        key: 3,
        value: '未开户',
      },
      {
        key: 6,
        value: '已开户',
      },
      {
        key: 7,
        value: '存管待审核',
      },
      {
        key: 8,
        value: '存管审核失败',
      },
    ];
    const enterpriseColumns = [
      {
        title: '企业编号',
        dataIndex: 'enterpriseNo',
        key: 'enterpriseNo',
      },
      {
        title: '企业名称',
        dataIndex: 'enterpriseName',
        key: 'enterpriseName',
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        render: text => (
          <span>
            {status.map(item => {
              if (item.key === text) {
                return item.value;
              }
            })}
          </span>
        ),
      },
      {
        title: '操作',
        fixed: 'right',
        width: 360,
        render: (text, record, index) => {
          return (
            <div key={index}>
              <a onClick={() => this.visibleDrawerInfo(true, text)}>查看</a>
              <Divider type="vertical" />
              {text.account ? (
                [<a onClick={() => this.changeOrderPwd(text)}>修改密码</a>]
              ) : (
                <a onClick={() => this.changeOpen(text)}>开户</a>
              )}
              <Divider type="vertical" />
              {text.bind ? (
                <a onClick={() => this.handleDelBankCard(text)}>解绑</a>
              ) : (
                <a onClick={() => this.handleBindCard(true, text)}>绑定</a>
              )}
              <Divider type="vertical" />
              <a onClick={() => this.handleUploadDrawer(true, text)}>资料上传记录</a>
              <Divider type="vertical" />
              <a onClick={() => this.handleUploadModalVisible(true, text)}>资料上传</a>
              {/*<Divider type="vertical"/>*/}
              {/*<a onClick={() => this.handleMemberVisible(true, text)}>联系人</a>*/}
            </div>
          );
        },
      },
    ];

    return (
      <PageHeaderWrapper title={data.userName} content={description(data)} action={action}>
        <Card title="企业列表" style={{ marginBottom: 24 }} bordered={false}>
          <Table
            pagination={false}
            loading={loading}
            dataSource={companyList}
            columns={enterpriseColumns}
          />
        </Card>
        <Card
          className={styles.tabsCard}
          bordered={false}
          tabList={operationTabList}
          onTabChange={this.onOperationTabChange}
        >
          <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>

          <Table
            pagination={pagination}
            loading={loading}
            dataSource={withdrawRecordList ? withdrawRecordList.data : []}
            columns={columns}
            onChange={this.handleStandardTableChange}
          />
        </Card>
        <DrawerComponent
          visible={visibleDrawer}
          descInfo={companyDesc ? companyDesc : {}}
          onClose={this.visibleDrawerInfo}
        />
        {visibleUploadDrawer ? (
          <Uploaddrawer visible={visibleUploadDrawer} onClose={this.handleUploadDrawer} />
        ) : (
          ''
        )}
        <ChangePwd
          handleModalVisible={this.handleModalVisible}
          handleChangePwd={this.handleChangePwd}
          modalVisible={modalVisible}
        />

        <UploadFile
          handleModalVisible={this.handleUploadModalVisible}
          handleUpload={this.handleUpload}
          modalVisible={uploadFileVisible}
        />
        <SelectBank
          bankList={bankList}
          handleBankModalVisible={this.handleBankModalVisible}
          handleSelectBank={this.handleSelectBank}
          bankModalVisible={bankModalVisible}
        />

        <MembersComponent
          onClose={this.handleMemberModalVisible}
          memberList={memberList}
          memberVisible={memberVisible}
        />
      </PageHeaderWrapper>
    );
  }
}

export default AdvancedProfile;
